package wang.wangby.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;


import lombok.Cleanup;


public class FileUtil {
	public static final String ENCODE="UTF-8";

	public static void copy(String from, String to) {
		try (RandomAccessFile fromFile = new RandomAccessFile(from, "rw");
				RandomAccessFile toFile = new RandomAccessFile(to, "rw");) {
			FileChannel fromChannel = fromFile.getChannel();
			FileChannel toChannel = toFile.getChannel();
			fromChannel.transferTo(0, fromChannel.size(), toChannel);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public static String getText(Class clazz,String path)  {
		try {
			InputStream in=clazz.getResourceAsStream(path);
			byte[] bs=read(in);
			return new String(bs,ENCODE);
		}catch(Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public static byte[] getBytes(Class clazz,String path) {
		InputStream in=clazz.getResourceAsStream(path);
		return read(in);
	}

	
	public static byte[] read(InputStream ins) {
		try {
			byte[] bytes = new byte[ins.available()];
			ins.read(bytes);
			return bytes;
		}catch(Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public static void createFile(String fileName,String content) throws FileNotFoundException, IOException {
		@Cleanup
		FileOutputStream out = new FileOutputStream(fileName);
		out.write(content.getBytes("UTF-8"));
	}
	
}
